package practice09.Paint;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class Drawing {
	//-----------------------------------------------------------------
	//  Sets up a frame containing a tabbed pane. The panel on each
	//  tab demonstrates a different layout manager.
	//-----------------------------------------------------------------
	public static void main (String[] args) {
		JFrame frame = new JFrame ("Drawing Board");
	    frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
	
	    DrawPanel tp = new DrawPanel();
	
	    frame.getContentPane().add(tp);
	    frame.pack();
	    frame.setVisible(true);
	}
}

class DrawPanel extends JPanel {
	CenterPanel p;
	JPanel container = new JPanel();
	public DrawPanel() {
		setLayout (new BorderLayout());

	  	JButton b = new JButton ("clear");
	  	JRadioButton red, blue, black;
	  	
      	p = new CenterPanel();
	  	p.setBackground(Color.yellow);
      	add (p, BorderLayout.CENTER);
      	add (b, BorderLayout.SOUTH);  
      	b.addActionListener(new ActionListener() {
      		public void actionPerformed (ActionEvent event) {
	  			p.clear();
	  		}
	  	});
      	
      	red = new JRadioButton("Red", true);
		blue = new JRadioButton("Blue");
		black = new JRadioButton("Black");
		
		red.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				p.brush = Color.red;
			}
  		});
		blue.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				p.brush = Color.blue;
			}
  		});
		black.addActionListener(new ActionListener() {
			public void actionPerformed (ActionEvent event) {
				p.brush = Color.black;
			}
  		});
		
		ButtonGroup group = new ButtonGroup();
		group.add(red);
		group.add(blue);
		group.add(black);
		container.add(red);
		container.add(blue);
		container.add(black);
		add(container, BorderLayout.NORTH);
	}
	
	private class CenterPanel extends JPanel {
		int rx, ry, rx2 = -1, ry2;
		Color back = Color.yellow;
		Color brush = Color.red;
		boolean CLEAR = true;
	
		CenterPanel() { 
			setPreferredSize(new Dimension(300,200));
			setBackground(Color.yellow);
			addMouseListener(new MouseAdapter() {
				public void mousePressed(MouseEvent e) {
					rx2 = e.getX();
					ry2 = e.getY();
				}
			});
			addMouseMotionListener(new MouseMotionAdapter() {
				public void mouseDragged(MouseEvent e) {
					rx = rx2;
					ry = ry2;
					rx2 = e.getX();
					ry2 = e.getY();
					if (rx>=0)	
						repaint();			
				}
			});
		}

		public void paint(Graphics g) {
			if (CLEAR) {	
				g.setColor(back);
				g.fillRect(0,0,getSize().width,getSize().height);
				CLEAR = false;
			}
			else {
				g.setColor(brush);
				g.drawLine(rx,ry,rx2,ry2);
			}
		}
	
		public void clear() {
			CLEAR = true;
			repaint();
		}
	};
}